<template>
  <el-card>
    <el-form
      :model="spuInfo"
      :rules="spuRules"
      :ref="ruleForm"
      label-width="100px"
    >
      <el-form-item :model="spuInfo" label="SPU名称" prop="spuName" required>
        <el-input
          v-model="spuInfo.spuName"
          placeholder="请输入SPU名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌" prop="tmId" required>
        <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in trademark"
            :label="tm.tmName"
            :value="tm.id"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description" required>
        <el-input
          type="textarea"
          :rows="4"
          v-model="spuInfo.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList" required>
        <el-upload
          :action="`${BASE_URL}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-success="handleAvatarSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuInfo.spuImageList"
          :before-upload="beforeAvatarUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-upload>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList" required>
        <el-select
          :placeholder="
            baseSaleAttrList.length > 1
              ? `还有${baseSaleAttrList.length}个`
              : `没有了`
          "
          v-model="spuInfo.spuSaleAttr"
          style="margin-bottom: 10px"
        >
          <el-option
            v-for="(baseSaleAttr, index) in baseSaleAttrList"
            :label="baseSaleAttr.name"
            :value="baseSaleAttr.name"
            :key="baseSaleAttr.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          size="medium"
          @click="toAddSpuSaleAttr"
          >添加销售属性</el-button
        >
        <el-table
          :data="spuInfo.spuSaleAttrList"
          border
          style="width: 100%; margin: 10px 0"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名"
            align="center"
            width="120"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值名称列表" align="center">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="spuSaleAttrValue.saleAttrValueName"
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, spuSaleAttrValue)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.isEdict"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                class="input-new-tag"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ 新增属性值</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="spuInfo.spuSaleAttrList.splice($index, 1)"
                >删除</el-button
              >
            </template></el-table-column
          >
        </el-table>
      </el-form-item>
      <el-button type="primary" style="margin-left: 100px" @click="submitForm"
        >保存</el-button
      >
      <el-button @click="$emit('setShowStatus', 'SPU_LIST')">取消</el-button>
    </el-form>
  </el-card>
</template>

<script>
import {
  reqGetAllTrademarkListData,
  reqGetAllBaseSaleAttrListData,
  reqSaveSpuInfoData,
  reqGetSpuImageListData,
  reqGetSpuSaleAttrListData,
  reqUpdateSpuInfoData,
} from "@/api/product/spu";
import { mapState } from "vuex";
export default {
  name: "SpuForm",
  props: ["currentSpuInfo"],
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      trademark: [], //品牌的
      seler: [], //属性
      fileList: [],
      inputValue: "",
      ruleForm: "ruleForm",
      //详情信息
      spuInfo: {
        spuName: "", //spu名称
        tmId: "", // 品牌对应的id
        description: "", // spu描述
        category3Id: -1, // 3id
        spuSaleAttr: "", // 表示spu的销售属性名  是后来额外添加的

        spuImageList: [], // 上传的图片至少得有imgName和imgUrl这两个属性
        spuSaleAttrList: [], // 相关的销售属性及属性值
        // 将待编辑的数据展开到这里来
        ...this.currentSpuInfo,
      },

      //校验规则
      spuRules: {
        spuName: [
          { required: true, message: "请填写Spu名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度应该在2--10之间", trigger: "blur" },
        ],
        tmId: [
          {
            required: true,
            message: "请选择一个品牌",
            trigger: "change",
          },
        ],
        description: [
          { required: true, message: "请输入Spu描述", trigger: "blur" },
        ],
        spuImageList: [
          {
            required: true,
            type: "array",
            message: "请至少上传一张图片",
            trigger: "change",
          },
        ],
        spuSaleAttrList: [
          {
            required: true,
            type: "array",
            message: "请至少添加一个销售属性",
            trigger: "change",
          },
        ],
      },
    };
  },
  /* mounted() {
    try {
      if (this.spuInfo.id) {
        this.getSpuImageListData();
        this.getSpuSaleAttrListData();
      }
      this.getAllTrademarkListData();
      this.getAllBaseSaleAttrListData();
    } catch (error) {
      this.$message({
        type: "info",
        message: "获取属性失败了...",
      });
    }
  }, */
  async mounted() {
    //0.发送请求获取SPU品牌属性和销售属性的值，用Promise.all是接力得的意思 有一个成功则为成功，如果一个失败就失败
    try {
      let promises = [
        reqGetAllTrademarkListData(),
        reqGetAllBaseSaleAttrListData(),
      ];
      const { id } = this.spuInfo;
      if (id) {
        promises = promises.concat(
          [reqGetSpuImageListData(id)],
          reqGetSpuSaleAttrListData(id)
        );
      }
      const [
        responseTrademarkList,
        responseBaseSaleAttrList,
        responseSpuImageList,
        responseSpuSaleAttrList,
      ] = await Promise.all(promises);
      this.trademark = responseTrademarkList.data;
      this.seler = responseBaseSaleAttrList.data;
      console.log("1111", responseBaseSaleAttrList, responseTrademarkList);
      // console.log("222", reqGetSpuImageListData, reqGetSpuImageListData);
      if (responseSpuImageList && responseSpuSaleAttrList) {
        this.spuInfo.spuImageList = responseSpuImageList.data.map((item) => {
          return {
            ...item,
            name: item.imgName,
            url: item.imgUrl,
          };
        });
        this.spuInfo.spuSaleAttrList = responseSpuSaleAttrList.data;
        console.log(responseSpuSaleAttrList, "能不能把你打印清掉");

        console.log("222", this.spuInfo.spuSaleAttrList);
      }
    } catch (err) {
      alert("获取属性失败!", err);
    }
  },

  computed: {
    ...mapState("categoryList", ["category3Id"]),
    // 销售属性的
    baseSaleAttrList() {
      return this.seler.filter((item) => {
        return !this.spuInfo.spuSaleAttrList.find((ser) => {
          return item.name === ser.saleAttrName;
        });
      });
    },
  },

  methods: {
    // 1，删除照片
    handleRemove(file, fileList) {
      console.log("filelist", file, fileList);
      this.spuInfo.spuImageList = file.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.response?.data || item.url,
        };
      });
    },

    // 2. 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url; //转化上传的图片真实地址 放到url
      this.dialogVisible = true; //显示上传图片的对话框
    },

    // 3. 图片上传成功后 收集上传了的图片链接地址
    handleAvatarSuccess(res, file, f) {
      console.log("fffffffffff", f);
      console.log('res', res);
      console.log('file', file);
      this.spuInfo.spuImageList = f
      console.log('spu',this.spuInfo.spuImageList);
      this.spuInfo.spuImageList.push({
        imgName: f.name,
        imgUrl: f.url,
      });
      //console.log("pic", this.$refs[this.ruleForm]);
      this.$refs[this.ruleForm].clearValidate("spuImageList");
    },

    // 4. 图片上传前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是JPG格式");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB");
      }
      return isJPG && isLt2M;
    },

    /* // 5.  获取spu列表的所有数据
    async getAllTrademarkListData() {
      const res = await this.$API.spu.reqGetAllTrademarkListData();
      this.trademark = res.data;
    },

    // 6. 获取销售属性名列表数据 颜色——尺码——版本
    async getAllBaseSaleAttrListData() {
      const res = await this.$API.spu.reqGetAllBaseSaleAttrListData();
      console.log("getAllBaseSaleAttrListData", res);
      this.baseSaleAttrList = res.data;
    },

    // 7. 获取销售属性值列表数据
    async getSpuSaleAttrListData() {
      const res = await this.$API.spu.reqGetSpuSaleAttrListData(
        this.spuInfo.id
      );
      console.log("getSpuSaleAttrListData", res);
    },

    // 8. 根据spuId获取图片列表
    async getSpuImageListData() {
      const res = await this.$API.spu.reqGetSpuImageListData(this.spuInfo.id);
      console.log("getSpuImageListData", res);
      this.spuInfo.spuImageList = res.data.map((item) => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl,
        };
      });
    }, */

    // 9. 添加销售属性
    toAddSpuSaleAttr() {
      const id = this.seler.find(
        (item) => item.name === this.spuInfo.spuSaleAttr
      )?.id;
      this.spuInfo.spuSaleAttrList.push({
        baseSaleAttrId: id,
        isEdict: false,
        saleAttrName: this.spuInfo.spuSaleAttr,
        spuSaleAttrValueList: [],
      });
      this.spuInfo.spuSaleAttr = "";
    },
    // 9.1 删除spuSaleAttrValue属性标签
    handleClose(row, spuSaleAttrValue) {
      row.spuSaleAttrValueList.splice(
        row.spuSaleAttrValueList.indexOf(spuSaleAttrValue),
        1
      );
    },
    // 9.2 添加spuSaleAttrValue属性标签
    showInput(row) {
      this.$set(row, "isEdict", true); // 这样添加才有响应式
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 10. 触发输入框
    handleInputConfirm(row) {
      if (
        row.spuSaleAttrValueList.find(
          (item) => item.saleAttrValueName === this.inputValue
        )
      ) {
        this.$message({
          message: "属性值相同，请重新输入！",
          type: "warning",
        });
        row.isEdict = false;
        this.inputValue = "";
        return;
      }
      if (this.inputValue) {
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrName: row.saleAttrName,
          saleAttrValueName: this.inputValue,
        });
      }
      console.log("row", row);
      row.isEdict = false;
      this.inputValue = "";
    },
    // 11. 点击保存 添加到spuInfo
    submitForm() {
      this.$refs[this.ruleForm].validate(async (valid) => {
        if (valid) {
          const subm = this.spuInfo.spuSaleAttrList;
          if (
            subm.length &&
            !subm.every((item) => item.spuSaleAttrValueList.length)
          ) {
            this.$message({
              message: "必填销售属性必须填写，不能为空！",
              type: "warning",
            });
            return;
          }
          this.spuInfo.category3Id = this.category3Id;
          if (this.spuInfo.id) {
            // 更新spuInfo
            await this.$API.spu.reqUpdateSpuInfoData(this.spuInfo);
          } else {
            await reqSaveSpuInfoData(this.spuInfo);
          }
          // 提示用户操作成功
          this.$message({
            type: "success",
            message: "操作spuInfo成功了...",
          });
          //跳转到列表页
          this.$emit("setShowStatus", "SPU_LIST");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped></style>
